package com.ys.controller.api.business;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.itextpdf.text.Image;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ys.config.MenuId;
import com.ys.entity.business.TpProductActive;
import com.ys.entity.business.TpProductActiveComponent;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.sys.YsCol;
import com.ys.service.business.TpProductActiveService;
import com.ys.service.business.TpProductBasicComponentService;
import com.ys.service.business.YsbExportLogService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.PdfService;
import com.ys.service.sys.UploadService;
import com.ys.service.sys.PdfService.ListingSubDto;
import com.ys.util.ExportExcelUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

/**
 * Listing库
 */
@Controller
@RequestMapping("/api/inter/tpProductActive")
public class ApiInterTpProductActiveController {
	private static final Logger logger = LoggerFactory.getLogger(ApiInterTpProductActiveController.class);
	private static Long MENU_ID = 10184L;
	//子表
	private static Long MENU_ID_DETAIL = 10185L;

	private static Long MENU_ID_OPERATIONS = 10186L;//运营维护
	private static Long MENU_ID_STORAGE = 10187L;//仓储维护
	private static Long MENU_ID_LOGISTICS = 10188L;//物流维护
	private static Long MENU_ID_PURCHASE = 10189L;//采购维护
	private static Long MENU_ID_MANAGE = 10190L;//管理维护


	@Autowired
	private CommonApiService<TpProductActive> commonApiService;

	@Autowired
	private CommonApiService<TpProductActiveComponent> commonApiService1;

	@Autowired
	private TpProductActiveService tpProductActiveService;

	@Autowired
	private TpProductBasicComponentService tpProductBasicComponentService;

	@Autowired
	private YsbExportLogService ysbExportLogService;
	@Autowired
	private PdfService pdfService;

	//菜单id
	private Long menuId = MenuId.TP_ProductActive;

	/**
	 * 设置查询的cond的sql设置
	 * @param cond
	 * @return
	 */
	public TpProductActive setSeachSql(TpProductActive cond){
		//排序
		cond.setOrderby("A.CreateTime DESC");
		cond.addField("D.categoryCn AS commodityPl");
		cond.addField("U.CUser AS cUser");
		cond.addField("U.CUser AS cUser,U.VGsMc AS vgsMc,U.VGsJc AS vgsJc");

		cond.addField("PM.NameCn AS nameCn");
		cond.addField("PM.NameEn AS nameEn");
		cond.addField("YT.UsageCn AS usageCn");
		cond.addField("YT.UsageEn AS usageEn");
		cond.addField("MC.NameUnitCn AS nameUnit");

		cond.addField("U.Vgsjc AS vgsjc");
		cond.addField("U.Vgsbm AS vgsbm");

		cond.addLeftJoin("TB_BaseinfoSppl D ON  D.id = A.commodityPlId");
		cond.addLeftJoin("THR_OperateCompanyApply U ON  U.VGsBm = A.VgsBm");

		//品名、材质、
		cond.addLeftJoin("TB_BaseinfoSppm PM ON  PM.id = A.NameId AND 1=1");
		cond.addLeftJoin("TB_BaseinfoSpyt YT ON  YT.id = A.UsageId AND 1=1");
		cond.addLeftJoin("TB_BaseinfoDwmc MC ON  MC.id = A.NameUnitId AND 1=1");

		//cond.setIsUsable("1");//只显示启用

		return  cond;
	}

	/**
	 * 查询
	 */
	@RequiresPermissions("tpProductActive:view")
	@RequestMapping("/search")
	@ResponseBody
	public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute TpProductActive cond){
		try {
			cond = setSeachSql(cond);
			//权限
			cond = commonApiService.dataAuth(MENU_ID, cond);
			LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
			return tableVoJA;
		}catch (Exception e){
			logger.error("查询Listing库出错：",e.getMessage(),e);
			LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
			tableVoJA.setCode(1);
			tableVoJA.setMsg("查询出错，请稍后重试！");
			return tableVoJA;
		}
	}

	/**
	 * 查询
	 */
	@RequiresPermissions("tpProductActive:view")
	@RequestMapping("/searchForModal")
	@ResponseBody
	public LayuiTableVoJA searchForModal(Model model, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute TpProductActive cond,
			String selectedUkeys){
		cond.setIsUsable("1");//只显示启用
		cond.addLeftJoin("TP_ProductBasis B on B.Code = A.Code")
			.addField("(select ISNULL(sum(Num * BPrice),0) from TP_ProductBasisComponent where Pcode = A.Code) priceIn"); // 调拨单价
		
		cond.addLeftJoin("THR_OperateCompanyApply C on C.VGsBm = A.VGsBm")
			.addField("C.VGsBm vgsbm")
			.addField("C.VGsJc vgsjc");
		cond = setSeachSql(cond);
		//权限
		cond = commonApiService.dataAuth(MENU_ID, cond);
		LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
		return tableVoJA;
	}

	/**
	 * 查询
	 */
	@RequiresPermissions("tpProductActive:view")
	@RequestMapping("/searchForModal1")
	@ResponseBody
	public LayuiTableVoJA searchForModal1(@ModelAttribute TpProductActiveComponent cond,
			String selectedUkeys){
		cond = commonApiService1.dataAuth(menuId, cond);
		cond.addLeftJoin("TP_ProductActive B on A.Pcode = B.Code")
			.addLeftJoin("THR_OperateCompanyApply C on C.VGsBm = B.VGsBm")
			.addField("B.Code productCode,A.Name subName,A.Code subCode,A.Num subBomNumber,A.Bprice subBomPrice," +
					"B.Name productName,B.CodeMerge codeMerge,C.CUser operatorUserId");

		LayuiTableVoJA tableVoJA = commonApiService1.searchLay(cond);

		return tableVoJA;
	}

	/**
	 * 导出
	 */
	@RequestMapping("/export")
	@ResponseBody
	public R export(@ModelAttribute TpProductActive cond, String conditions){
		YsbExportLogService.ExportDto dto1 = ysbExportLogService.init(MENU_ID);
		try {
			cond = setSeachSql(cond);
			cond.setPage(0).setSize(99999);
//权限
			cond = commonApiService.dataAuth(MENU_ID, cond);
			//获取菜单字段数据
			List<YsCol> listField = new YsCol()
					.where("A.Code NOT IN ('id','pcode','ope','nameId','usageId','materialId','nameUnitId') ")
					.where("A.MenuId = "+MENU_ID)
					.setOrderby("A.MenuId ASC,A.SortNo ASC")
					.queryList();

			List<YsCol> listFieldBySon = new YsCol()
					.where("A.Code NOT IN ('id','pcode','name','code','num','remark','bprice','bprices','linkIn','linkInMark') ")
					.where("A.MenuId = "+MENU_ID_DETAIL)
					.setOrderby("A.SortNo ASC")
					.queryList();

			listFieldBySon.stream().forEach(item->listField.add(item));

			cond.addField("B.Name AS sonName");
			cond.addField("B.Code AS sonCode");
			cond.addField("B.Num AS sonNum");
			cond.addField("B.Remark AS sonRemark");
			cond.addField("B.Bprice AS sonBprice");
			cond.addField("B.Bprices AS sonBprices");
			cond.addField("B.LinkIn AS sonLinkIn");
			cond.addField("B.LinkInMark AS sonLinkInMark");
			cond.addField("STUFF((SELECT ',' + tpm.MaterialNameCn FROM TP_ProductMaterial tpm WHERE tpm.Type = 3 AND tpm.ProductCode = A.Code ORDER BY tpm.MaterialNameCn FOR XML PATH('')), 1, 1, '') AS materialCn");
			cond.addField("STUFF((SELECT ',' + tpm.MaterialNameEn FROM TP_ProductMaterial tpm WHERE tpm.Type = 3 AND tpm.ProductCode = A.Code ORDER BY tpm.MaterialNameCn FOR XML PATH('')), 1, 1, '') AS materialEn");

			cond.addLeftJoin("TP_ProductBasisComponent B ON B.Pcode = A.Code");
			cond.setOrderby("A.Code ASC,B.Code ASC");


			//权限
			//cond = commonApiService.dataAuth(MENU_ID, cond);

			//获取数据
			List<Map<String, Object>> listData = cond.queryMap();


			ExportExcelUtils<TpProductActive> util = new ExportExcelUtils<>(new TpProductActive());
			String toFilePath = util.exportExcel(listData, listField, "Listing库");

			UploadService.UploadDto dto2 = commonApiService.uploadLocalToServer(toFilePath);
			ysbExportLogService.updateSuccess(dto1.getId(), dto2.getUrl());;

			return R.ok("已经生成完毕");


		}catch (Exception e){
			logger.error("导出精品表出错：",e.getMessage(),e);
			ysbExportLogService.updateFail(dto1.getId());
			return R.error("生成失败，请联系客服");
		}
	}

	/**
	 * Listing库修改保存修改公共类
	 */
	public R editProductActive(Map<String, Object> params,Long menuId,boolean hasSonList,String editType){
		try {
			logger.info("Listing库修改保存传参："+params);
			//去除多余参数，只保留有权限编辑的参数
			Map<String, Object> paramsNew = tpProductActiveService.removeSurplusParams(params,menuId,hasSonList);
			//参数验证
			String errorMsg = tpProductActiveService.checkParams(paramsNew,menuId);
			if(errorMsg!=null && !"".equals(errorMsg)){
				return R.error(errorMsg);
			}
			logger.info("Listing库修改保存传参,去除多余参数后："+paramsNew);
			//判断是否图片是否上传合适
			if (editType.equals("storage")){
				try {
					Image image = Image.getInstance(params.get("img").toString());
				} catch (Exception e) {
					if (e.getMessage().contains("is not a recognized imageformat.")){
						return R.error("商品图片异常,请重新另存为其他格式后再上传!");
					}
				}

			}
			//修改Listing库主表信息，以及关联信息
			tpProductActiveService.editAndCorrelation(paramsNew);
			//如果有权限修改子表信息
			if(hasSonList && params.get("subData")!=null){
				JSONArray subData = JSON.parseArray(params.get("subData").toString());
				//去除多余参数，只保留有权限编辑的参数
				List<Map<String, Object>> paramsNewByComponent = tpProductBasicComponentService.removeSurplusParams(subData,MENU_ID_DETAIL);
				//子件参数验证
				String errorMsgByComponent = tpProductBasicComponentService.checkParams(paramsNewByComponent,MENU_ID_DETAIL);
				if(errorMsgByComponent!=null && !"".equals(errorMsgByComponent)){
					return R.error(errorMsgByComponent);
				}
				//子件信息保存
				logger.info("Listing库子件信息保存传参："+paramsNewByComponent);
				//return saveComponent( paramsNewByComponent);
				return tpProductBasicComponentService.saveAndProductActive( paramsNewByComponent,Long.parseLong(params.get("id").toString()),editType);
			}
			return R.ok();
		} catch (Exception e) {
			logger.error("修改出错：",e.getMessage(),e);
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}



	/**
	 * 删除
	 */
	@RequestMapping("/toDel")
	@ResponseBody
	public R toDel(HttpServletRequest request,@RequestParam Map<String, Object> params){
		try {
			String ids = params.get("ids").toString();
			String[] idArr = ids.split(",");
			List<String> idList = new ArrayList<>();
			Collections.addAll(idList,idArr);
			String code = params.get("code").toString();
			//删除
			return tpProductBasicComponentService.delAndProductActive(idList,code);
		} catch (Exception e) {
			logger.error("子表信息删除出错：",e.getMessage(),e);
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}


	/**
	 * 运营维护修改
	 */
	@RequiresPermissions("tpProductActive:operationsEdit")
	@RequestMapping("/toEditByOperations")
	@ResponseBody
	public R toEditByOperations(HttpServletRequest request, @RequestParam Map<String, Object> params){
		return editProductActive(params,MENU_ID_OPERATIONS,false,"operations");
	}

	/**
	 * 仓储维护修改
	 */
	@RequiresPermissions("tpProductActive:storageEdit")
	@RequestMapping("/toEditByStorage")
	@ResponseBody
	public R toEditByStorage(HttpServletRequest request, @RequestParam Map<String, Object> params){
		return editProductActive(params,MENU_ID_STORAGE,false,"storage");
	}

	/**
	 * 物流维护修改
	 */
	@RequiresPermissions("tpProductActive:logisticsEdit")
	@RequestMapping("/toEditByLogistics")
	@ResponseBody
	public R toEditByLogistics(HttpServletRequest request, @RequestParam Map<String, Object> params){
		return editProductActive(params,MENU_ID_LOGISTICS,false,"logistics");
	}

	/**
	 * 采购维护修改
	 */
	@RequiresPermissions("tpProductActive:purchaseEdit")
	@RequestMapping("/toEditByPurchase")
	@ResponseBody
	public R toEditByPurchase(HttpServletRequest request, @RequestParam Map<String, Object> params){
		return editProductActive(params,MENU_ID_PURCHASE,true,"purchase");
	}

	/**
	 * 管理维护修改
	 */
	@RequiresPermissions("tpProductActive:manageEdit")
	@RequestMapping("/toEditByManage")
	@ResponseBody
	public R toEditByManage(HttpServletRequest request, @RequestParam Map<String, Object> params){
		return editProductActive(params,MENU_ID_MANAGE,false,"manage");
	}


	/**
	 * 批量修改精品库和商品库的公司编码信息
	 */
	//@RequiresPermissions("tpProductActive:updateVgsbm")
	@RequestMapping("/updateVgsbm")
	@ResponseBody
	public R updateVgsbm(HttpServletRequest request, @RequestParam Map<String, Object> params){

		List<String> codeList = new ArrayList<>();
		String codes = params.get("codeList").toString();
		String[] codeArr = codes.split(",");
		Collections.addAll(codeList,codeArr);

		String vgsbm = params.get("vgsbm").toString();
		return tpProductActiveService.updateVgsbmByList(codeList,vgsbm);
	}


	/**
	 * 生成商品标
	 */
	@RequiresPermissions("tpProductActive:printGoods")
	@RequestMapping("/generateGoodsPDF")
	@ResponseBody
	public R generateGoodsPDF(Long id){

		if (id == null) {
			return R.error("ID不能为空");
		}
		
		TpProductActive tpProductActive = new TpProductActive().setId(id).queryFirst();
		String productCode = tpProductActive.getCode();
		String productName = tpProductActive.getName();
		String vgsbm = tpProductActive.getVgsBm();
		ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm(vgsbm).queryFirst();
		String vgsjc = thrOperateCompanyApply.getVgsjc();
		
		List<TpProductActiveComponent> listSub = new TpProductActiveComponent().setPcode(productCode).queryList();
		List<ListingSubDto> listData = new ArrayList<ListingSubDto>();
		for(TpProductActiveComponent sub : listSub) {
			String code = sub.getCode();
			String name = sub.getName();
			listData.add(new ListingSubDto(code, name));
		}
		
		String url = pdfService.generateGoodsPDF_Listring(productCode, productName, vgsbm, vgsjc, listData);
		return R.ok(url);
	}


	/**
	 * 商品复制
	 */
	@RequiresPermissions("tpProductActive:copyGoods")
	@RequestMapping("/copyGoods")
	@ResponseBody
	public R copyGoods(HttpServletRequest request, @RequestParam Map<String, Object> params){
		try {
			List<String> codeList = new ArrayList<>();
			String codes = params.get("codes").toString();
			String[] codeArr = codes.split(",");
			Collections.addAll(codeList,codeArr);

			return tpProductActiveService.copyGoods(codeList);
		}catch (Exception e){
			logger.error("出错：",e.getMessage(),e);
			return R.error("操作失败，请稍后重试！");
		}

	}
	/**
	 * listing库弹出框采购计划单使用
	 */
	@RequestMapping("/searchForModalByPlan")
	@ResponseBody
	public LayuiTableVoJA searchForModalByPlan(Model model, HttpServletRequest request, HttpServletResponse response,
											   @ModelAttribute TpProductActive cond
	){

		cond = setSeachSql(cond);
		//权限
		cond = commonApiService.dataAuth(menuId, cond);
		cond.setIsUsable("1");//只显示启用

		return commonApiService.searchLay(cond);
	}


}